package com.ky.course.controller;

import cn.hutool.core.convert.NumberWithFormat;
import com.ky.common.config.SystemConfig;
import com.ky.common.param.OrderAdd;
import com.ky.common.util.JwtUtil;
import com.ky.common.vo.R;
import com.ky.user.entity.Orders;
import com.ky.course.mapper.OrdersMapper;
import com.ky.course.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author zpa
 * @since 2024-06-20
 */
@RestController
@RequestMapping("/course/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrdersMapper ordersMapper;
    @RequestMapping("/findAllOrders")
    public R findAllOrders()
    {
        return ordersService.findAllOrders();
    }
    /**
     * 未付款订单
     */
    @RequestMapping("/findAllOrderByType")
    public R findAllOrderByType(@RequestParam(value = "status") Integer status)
    {
        return ordersService.findAllOrderByType(status);
    }
    /**
     * 创建订单
     * @param request
     * @param orderAdd
     * @return
     */
    @RequestMapping("/createOrder")
    public R createOrder(HttpServletRequest request , @RequestBody OrderAdd orderAdd){

        if(orderAdd==null){
            return R.fail("参数不能为空");
        }
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();
        if (id == null){
            return R.fail("请先登录");
        }
        // return ordersService.createOrder(token,orderAdd);
        Orders orders = new Orders();
        orders.setCourseId(orderAdd.getCourseId());
        orders.setAddressId(orderAdd.getAddressId());
        orders.setUserId(id);
        orders.setStatus(1);
        orders.setTotalAmount(orderAdd.getPrice());
        orders.setOrderTime(new Date());
        ordersMapper.insert(orders);
        return R.ok("创建订单成功");
    }
}

